/*
 * @Author: yangzonglong
 * @Date: 2021-05-11 15:26:13
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 17:01:22
 * @Auditor:
 */
import React, { useState, useRef, forwardRef, useImperativeHandle, useCallback, useMemo } from 'react';
import { Modal } from 'antd';
import { units } from '@library';
import View from '../../../../components/fd/view/View';
import { ViewRefProps } from '../../../../components/fd/interface';
import { addOrUpdateByUrl } from './api';
import { ModalFormRef } from './interface';
import { getFormUrlAndQuery } from './../../eval';

const bodyStyle: React.CSSProperties = {
  height: '70vh',
  overflow: 'auto',
  display: 'flex',
  flexDirection: 'column',
  position: 'relative'
};

const ModalForm = (props: { callback: () => void; formName?: string; }, ref: React.Ref<ModalFormRef>) => {

  const [visible, setVisible] = useState(false);

  const formRef = useRef<ViewRefProps>(null);
  const [formData, setFormData] = useState<object>({});
  const [disabled, setDisabled] = useState(false);
  const [url, setUrl] = useState('');
  const [state, setState] = useState({ list: [], formDesc: '', formName: '', enviromentConfig: undefined });
  const [footer, setFooter] = useState({});

  const onOK = useCallback(async () => {
    const data = await formRef.current?.validateFields();
    const res = await addOrUpdateByUrl(url, { ...formData, ...data });
    if (res) {
      setVisible(false);
      props.callback();
    }
  }, [formData, props, url]);

  useImperativeHandle(ref, () => ({
    show: (data: object, name: string, url?: string, disabled?: boolean) => {
      setFormData(data);
      setUrl(url || '');
      setDisabled(disabled!);
      formRef.current?.setFieldsValue(data);
      if (window.location.href.indexOf('shell/app') > -1) {
        const { url, where } = getFormUrlAndQuery(decodeURIComponent(name));

        units.serverLoading(url, { where }).then(res => {
          if (res) {
            setVisible(true);
            setState(res?.content ? {
              list: JSON.parse(res.content).list,
              enviromentConfig: res.enviromentConfig ? JSON.parse(res.enviromentConfig) : undefined,
              formDesc: res.formDesc,
              formName: res.formName,
            } : { list: [], formDesc: '', formName: '', enviromentConfig: undefined });
          } else {
            units.message.error(`未找到[${name}]`);
          }
        });
      } else {
        units.serverLoading('/bk/api/fd/Form/findOne', {
          where: {
            'formName': decodeURIComponent(name)
          }
        }).then(result => {
          if (result) {
            setVisible(true);
            setState(result.content ? {
              list: JSON.parse(result.content).list,
              enviromentConfig: result.enviromentConfig ? JSON.parse(result.enviromentConfig) : undefined,
              formDesc: result.formDesc,
              formName: result.formName,
            } : { list: [], formDesc: '', formName: '', enviromentConfig: undefined });
          }
        });
      }
    },
    hide: () => {
      setVisible(false);
    }
  }));

  const _View = useMemo(() => {
    return <View setFooter={setFooter} disabled={disabled} structure={state} ref={formRef} data={formData} formInfo={{ formDesc: state.formDesc, formName: state.formName }} />;
  }, [disabled, formData, state]);

  return (
    <Modal
      destroyOnClose
      title={props.formName}
      {...(disabled ? { footer: null } : footer)}
      onOk={onOK}
      visible={visible}
      onCancel={() => setVisible(false)}
      width={1200}
      bodyStyle={bodyStyle}>
      {_View}
    </Modal>
  );
};

export default forwardRef(ModalForm);
